package com.china.api.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.china.itapi.common.entity.Users;


public class IsLogin implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		  HttpServletRequest req=(HttpServletRequest)request;
		  HttpServletResponse res=(HttpServletResponse)response;
		  String contextPath=req.getContextPath();
		  String reqURI=req.getRequestURI();
		  System.out.println(contextPath);
		  System.out.println(reqURI);
		if (reqURI.indexOf("/login.jsp") > -1||reqURI.indexOf("/main.css") > -1||
				reqURI.indexOf("/loginAction") > -1||
				reqURI.indexOf("/mainAction") > -1||
				reqURI.indexOf("/listAction") > -1||
				reqURI.indexOf("/downfileAction") > -1||
				reqURI.indexOf("/images/") > -1||
                reqURI.indexOf("/upload/") > -1||
				reqURI.indexOf("/detailAction") > -1) {
			chain.doFilter(req, res);
			return;
		}

		// 判断如果没有取到员工信息,就跳转到登陆页面
		if (!islogin(req)) {
			// 跳转到登陆页面
			res.sendRedirect(contextPath+"/login.jsp");
		} else {
			// 已经登陆,继续此次请求
			chain.doFilter(req, res);
		}

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}
	
	private boolean islogin(HttpServletRequest req) {    
			   
	        // 处理用户登录
		Users user = (Users) req.getSession().getAttribute("user");
		if (user != null) {
			return true;
		} else {
			return false;
		}  
	} 

}
